package com.nineclock.system.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SmsService smsService;

    @Override
    public SysUserDTO queryUser(String username) {

        // 查询用户名或手机号等于username 且 已激活的用户
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username)
                .or()
                .eq(SysUser::getMobile, username);
        wrapper.eq(SysUser::getStatus, 1);


        SysUser sysUser = userMapper.selectOne(wrapper);

        if(sysUser != null){
            SysUserDTO userDTO = BeanHelper.copyProperties(sysUser, SysUserDTO.class);
            return userDTO;
        }

        return null;
    }

    @Override
    public void register(SysRegisterDTO registerDTO) {
        // 参数校验
        if(registerDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 校验验证码
        Boolean verifyResult = smsService.verifyCode(registerDTO.getMobile(),
                registerDTO.getCheckcode(), SMSConstant.SMS_TYPE_REGISTER);

        if(!verifyResult){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        // 插入用户数据到数据库
        SysUser sysUser = new SysUser();
        sysUser.setPassword(new BCryptPasswordEncoder().encode(registerDTO.getPassword()));
        sysUser.setMobile(registerDTO.getMobile());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus((short)1);

        userMapper.insert(sysUser);
    }
}
